package frist50;

public class T0008 {
    public int myAtoi(String s) {
        if (s.length() == 0) return 0;
        int a, b = 1;
        long sum = 0;
        for (a = 0; a < s.length(); a++) {
            if (s.charAt(a) != ' ') break;
        }
        if(a==s.length())return 0;
        if (s.charAt(a) == '-') {
            b = -1;
            a += 1;
        } else if(s.charAt(a) == '+') {
            a += 1;
        }
        for (int i = a; i < s.length(); i++) {
            if (!Character.isDigit(s.charAt(i))) break;
            sum = sum * 10 - Integer.parseInt(String.valueOf(s.charAt(i)));
            if (sum < Integer.MIN_VALUE) break;
        }
        sum = b * sum * (-1);
        if (sum > Integer.MAX_VALUE) return Integer.MAX_VALUE;
        if (sum < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        return (int) sum;
    }
}
